<?php

namespace App\Http\Controllers\Card;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Classs;
use App\Card;
class IndexController extends Controller
{
    public function getInsert() {
        //名片添加页面
        return view('admin/insert/add');
    }

    public function getClass(Request $request) {
        //添加分组
        //接受用户添加的分组名和用户id
        $classname = $request->classname;
        $uid = $request->uid;
        //向数据库里添加分组名和用户id
        $class = new \App\Classs();
        $class -> classname = $classname;
        $class -> uid = $uid;
        $res = $class -> save();
        if($res) {
            return "添加成功";
        } else {
            return "添加失败";
        }
    }

    public function getClassid(Request $request) {
        //接受ajax查询分组名
        $uid = $request->id;
        $data = Classs::where('uid','=',$uid)->get(['classname']);
        return $data;
    }
    public function postAdd(Request $request) {
        //添加名片
         $card = new \App\Card();
         $card->uid = $request->id;
         $card->name = $request->name;
         $card->position = $request->position;
         $card->company = $request->company;
         $card->address = $request->address;
         $card->cell = $request->cell;
         $card->url = $request->url;
         $card->email = $request->email;
         $card->classify=$request->class;
         $card->classify = $request->class;
         $res = $card->save();
        if($res) {
            return redirect('admin/index/list')->with('success','添加成功');
        } else {
            return back()->with('error','添加失败');
        }
    }

    public function getEdit(Request $request) {
        //名片修改页面
        //接收用户要修改名片的id
        $id = $request->id;
        $card = Card::find($id);
        return view('admin/insert/edit',['data'=>$card]);
    }

    public function postUpdate(Request $request) {
        //名片修改操作
        $data = $request->all();
        $card = Card::find($data['id']);
        $card->name = $data['name'];
        $card->position = $data['position'];
        $card->company = $data['company'];
        $card->address = $data['address'];
        $card->cell = $data['cell'];
        $card->url = $data['url'];
        $card->email = $data['email'];
        $card->classify=$data['class'];
        $card->classify = $data['class'];
        $res = $card->save();
        if($res) {
            return redirect('admin/index/list')->with('success','修改成功');
        } else {
            return back()->with('error','修改失败');
        }
    }

    public function getDelete(Request $request) {
        //名片删除操作
        $res = Card::where('id','=',$request->id)->delete();
        if($res) {
            return redirect('admin/index/list')->with('success','删除成功');
        } else {
            return back()->with('error','删除失败');
        }
    }
}
